<template>
  <div class="message" :class="type">
    <div class="message-content">
      <div class="message-text" v-html="formattedHtml"></div>
    </div>
  </div>
</template>

<script>
import { computed } from "vue";
import MarkdownIt from "markdown-it";
import DOMPurify from "dompurify";

const md = new MarkdownIt({
  breaks: true,
  linkify: true,
  html: false,
});

export default {
  props: {
    message: {
      type: Object,
      required: true,
      validator: (value) => {
        return value && ("question" in value || "answer" in value);
      },
    },
    type: {
      type: String,
      default: "answer",
    },
  },
  setup(props) {
    const formattedHtml = computed(() => {
      if (!props.message) return "";
      const text =
        props.type === "question"
          ? props.message.question || ""
          : props.message.answer || "";
      const rendered = md.render(String(text));
      return DOMPurify.sanitize(rendered);
    });

    return {
      formattedHtml,
    };
  },
};
</script>

<style scoped>
.message {
  max-width: 78%;
  margin-bottom: 0.5rem;
  display: flex;
}

.message.question {
  margin-left: auto;
  justify-content: flex-end;
}

.message.answer {
  margin-right: auto;
  justify-content: flex-start;
}

.message-content {
  padding: 0.75rem 1rem;
  border-radius: 14px;
  line-height: 1.6;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.02);
}

.message.question .message-content {
  background: linear-gradient(180deg, #1890ff 0%, #1677ff 100%);
  color: white;
  border-top-right-radius: 4px;
}

.message.answer .message-content {
  background-color: #ffffff;
  color: #333;
  border: 1px solid #eef0f3;
  border-top-left-radius: 4px;
}

.message-text {
  word-break: break-word;
}

/* Markdown 基础样式 */
.message-text h1,
.message-text h2,
.message-text h3 {
  margin: 0.2rem 0 0.4rem;
  line-height: 1.25;
}
.message-text h1 {
  font-size: 1.25rem;
}
.message-text h2 {
  font-size: 1.1rem;
}
.message-text h3 {
  font-size: 1rem;
}

.message-text p {
  margin: 0.4rem 0;
}
.message-text ul,
.message-text ol {
  margin: 0.4rem 0 0.4rem 1.2rem;
}
.message-text li {
  margin: 0.2rem 0;
}
.message-text hr {
  border: 0;
  border-top: 1px solid #e5e7eb;
  margin: 0.6rem 0;
}
.message-text blockquote {
  margin: 0.4rem 0;
  padding: 0.4rem 0.6rem;
  border-left: 3px solid #e5e7eb;
  background: #fafafa;
}
.message-text code {
  background: #f5f5f5;
  padding: 0 0.25rem;
  border-radius: 4px;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
    "Liberation Mono", "Courier New", monospace;
}
.message-text pre code {
  display: block;
  padding: 0.6rem;
  white-space: pre-wrap;
}
.message-text a {
  color: #1677ff;
  text-decoration: underline;
}
</style>
